package com.zqwh.yj.sdk.utils;

import android.content.Context;
import android.media.MediaPlayer;


import com.zqwh.yj.sdk.R;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by eason.yang on 2017/8/21.
 */

public class BxwVoiceUtil {
    private static MediaPlayer mPlayer;
    private static boolean playing = false;
    private static Timer beeTimer;

    public static void beeVoice(Context context){
        playOnce(context, R.raw.bee);
    }

    public static void beeBeeVoice(Context context){
        playOnce(context, R.raw.beebee);
    }

    public static void startBeeLoop(final Context context, int period){
        beeTimer = new Timer(true);
        beeTimer.schedule(new TimerTask() {
            public void run() {
                playOnce(context, R.raw.beebee);
            }
        }, 0 , period);
    }

    public static void cancelBeeLoop(){
        if (beeTimer != null){
            beeTimer.cancel();
            beeTimer = null;
        }
    }

    public static void playOnce(Context context, int fileId){
        if (!playing) {
            mPlayer = MediaPlayer.create(context, fileId);
            mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mediaPlayer) {
                    mediaPlayer.stop();
                    mediaPlayer.release();
                    playing = false;
                }
            });
            mPlayer.start();
            playing = true;
        }
    }

    public static void playNow(Context context, int fileId){
        mPlayer = MediaPlayer.create(context, fileId);
        mPlayer.start();
    }

    public static void playOnce(final String dataSource){
        if (!playing) {
            mPlayer = new MediaPlayer();
            try {
                mPlayer.setDataSource(dataSource);
                mPlayer.setLooping(false);
                mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mediaPlayer) {
                        mediaPlayer.stop();
                        mediaPlayer.release();
                        playing = false;
                    }
                });
                mPlayer.prepare();
                mPlayer.start();
                playing = true;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
